<?php

namespace app\model\Dao\Redis;

use think\cache\driver\Redis;
use think\facade\Cache;

class Base
{
    protected $keyprefix = 'MyAppName';
    // 拼接符号
    public $modelName = '';

    /**
     * redis 链接驱动
     *
     * @var \think\cache\Driver
     */
    protected $driver;
    protected $connection = 'redis';

    function __construct($keyprefix = '')
    {
        empty($keyprefix) || $this->keyprefix = $keyprefix;
        $this->driver = Cache::store($this->connection);
    }

    /**
     * 获取redis驱动
     *
     * @return \think\cache\Driver
     */
    public function getDriver()
    {
        
        return $this->driver;
    }

    /**
     * 获取缓存key
     *
     * @return void
     */
    public function k(string  ...$k)
    {
        $prefixkeys = [$this->keyprefix];
        if (! empty($this->modelName)) {
            $prefixkeys[] = $this->modelName;
        }
        $ks = array_merge($prefixkeys, $k);
        return implode(Keys::CONCAT, $ks);
    }
    
    /**
     * 模糊过期时间，防缓存雪崩
     *
     * @param int $expire
     * @return int
     */
    public function ttlBlur(int $expire)
    {
        if ($expire < 60) {
            return $expire;
        }
        return $expire - 30 + rand(0, 60);
    }

}

